package com.common.utils.executorsutils.pool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 功能描述；
 *  随机扣减库存同时开启5个线程并发
 * 扣减库存直到下次扣减的库存小于0停止
 *
 */
public class ExecutorThread {


    //扣减线程
    private DeductionStoreThread deductionStore;

    public ExecutorThread(DeductionStoreThread deductionStore) {
        this.deductionStore = deductionStore;
    }

    public void excutorThread(){
        int numThreads = 5;
        ExecutorService executorService = Executors.newFixedThreadPool(numThreads);
        List<Future<?>> futures = new ArrayList<>();

        //随机生成扣减库存数量
        for(int i=0;i<1000;i++){
            Future<?> future = executorService.submit(deductionStore);
            futures.add(future);
        }

        // 等待所有任务完成
       for (Future<?> future1 : futures) {
            try {
                Integer storenumber = (Integer)future1.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 关闭线程池
        executorService.shutdown();
    }


    //测试功能
    public static void main(String[] args) throws InterruptedException {
        // 在多个线程中获取单例对象
        Store store = Store.getInstance();
        Runnable task = () -> {
            DeductionStoreThread deductionStore = new DeductionStoreThread(0,store);
            ExecutorThread executorThread = new ExecutorThread(deductionStore);
            executorThread.excutorThread();
        };

        ArrayList<Thread> threads = new ArrayList<>();
        // 创建多个线程
        for(int i=0;i<100; i++){
            Thread thread = new Thread(task);
            threads.add(thread);
        }
        // 启动线程
        for(Thread thread : threads){
            thread.start();
        }
        //等待线程执行完毕
        for(Thread thread : threads){
            thread.join();
        }

        System.out.print("原始库存数量: 1000000 \n");
        System.out.print("一共扣减库存数量:" +store.getKjcount() +"\n");
        System.out.print("最终剩余库存数量:" +store.getCount() +"\n");
    }
}
